package com.sjz.myfrist;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/***
 *   Activity 之间传送数据  发送端  点击按钮后可以通过Intent传递数据  带返回值
 *    发送带返回值的方法startActivityForResult  方法废弃了
 *   onActivityResult  处理返回的值
 */
public class ActSendResultTwoActivity extends AppCompatActivity  {
    private static final int REQUEST_CODE = 1;
    private EditText editText;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_send_result_two);
        editText = findViewById(R.id.activity_send2_editText);
        Button sendButton = findViewById(R.id.activity_send2_sendButton);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String dataToSend = editText.getText().toString();
                Intent intent = new Intent(ActSendResultTwoActivity.this, ActReceiveResultTwoActivity.class);
                intent.putExtra("data", dataToSend);
                startActivityForResult(intent, REQUEST_CODE);//发送消息，并且设置可以取回调方法
            }
        });

    }

    /***
     * 处理回传数据： 使用onActivityResult()方法来处理从ReceiveDataActivity回传的数据。
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {//验证请求码
            if (resultCode == RESULT_OK && data != null) {//验证返回码
                String receivedData = data.getStringExtra("dataFromReceive");
                // 处理回传的数据
                System.out.println(receivedData);
                editText.setText(receivedData);
            }
        }
    }
}